﻿Namespace Global.Runa.UI.Threading

    Friend MustInherit Class DispatcherOperationTaskSource

        Public MustOverride Function GetTask() As Task
        Public MustOverride Sub Initialize(ByVal operation As DispatcherOperation)
        Public MustOverride Sub SetCanceled()
        Public MustOverride Sub SetException(ByVal exception As Exception)
        Public MustOverride Sub SetResult(ByVal result As Object)

    End Class

    Friend Class DispatcherOperationTaskSource(Of TResult)
        Inherits DispatcherOperationTaskSource

        Private _taskCompletionSource As TaskCompletionSource(Of TResult)

        Public Overrides Function GetTask() As Task
            If (Me._taskCompletionSource Is Nothing) Then
                Throw New InvalidOperationException
            End If
            Return Me._taskCompletionSource.Task
        End Function

        Public Overrides Sub Initialize(ByVal operation As DispatcherOperation)
            If (Not Me._taskCompletionSource Is Nothing) Then
                Throw New InvalidOperationException
            End If
            Me._taskCompletionSource = New TaskCompletionSource(Of TResult)(New DispatcherOperationTaskMapping(operation))
        End Sub

        Public Overrides Sub SetCanceled()
            If (Me._taskCompletionSource Is Nothing) Then
                Throw New InvalidOperationException
            End If
            Me._taskCompletionSource.SetCanceled()
        End Sub

        Public Overrides Sub SetException(ByVal exception As Exception)
            If (Me._taskCompletionSource Is Nothing) Then
                Throw New InvalidOperationException
            End If
            Me._taskCompletionSource.SetException(exception)
        End Sub

        Public Overrides Sub SetResult(ByVal result As Object)
            If (Me._taskCompletionSource Is Nothing) Then
                Throw New InvalidOperationException
            End If
            Me._taskCompletionSource.SetResult(DirectCast(result, TResult))
        End Sub

    End Class

End Namespace
